package config

import (
	"fmt"
	"gopkg.in/yaml.v3"
	"os"
	"vpn/app/utils/file_handle"
)

var defaultConf = &BaseConfig{
	LogConfig: LogConfig{
		FilePath:   "/var/log/vpn-backend/vpn.log",
		Level:      "Info",
		Size:       5, // MB
		Count:      5, //轮次
		IsToStdout: false,
	},
	OpenvpnConfig: OpenvpnConfig{
		ConfigPath:         "/etc/openvpn/server.conf",
		InstallScriptPath:  "/root/vpn-backend/install.sh",
		SaveConfScriptPath: "/root/vpn-backend/save_conf.sh",
		EnvConfPath:        "/root/vpn-backend/openvpn.env",
	},
	JwtConfig: JwtConfig{
		JwtTokenSignKey: "vpn-backend", //设置token生成时加密的签名
		JwtExpireAt:     28800,         // 8小时
	},
	DefaultPort:      89,
	BasePath:         "/root/vpn-backend/",
	YamlConfPath:     "/root/vpn-backend/vpn-backend.yaml",
	UserInfoFilePath: "/root/vpn-backend/userInfo.json",
}

type OpenvpnConfig struct {
	ConfigPath         string `yaml:"ConfigPath"`
	InstallScriptPath  string `yaml:"installScriptPath"`
	SaveConfScriptPath string `yaml:"saveConfScriptPath"`
	EnvConfPath        string `yaml:"envConfPath"`
}

// LogConfig 结构体
type LogConfig struct {
	FilePath   string `yaml:"filePath"`
	Level      string `yaml:"level"`
	Size       int64  `yaml:"size"`
	Count      int64  `yaml:"count"`
	IsToStdout bool   `yaml:"is_to_stdout"`
}

type JwtConfig struct {
	JwtTokenSignKey string `yaml:"JwtTokenSignKey"`
	JwtExpireAt     int64  `yaml:"jwtExpireAt"`
}

// Config 结构体
type BaseConfig struct {
	LogConfig        LogConfig     `yaml:"logConfig"`
	OpenvpnConfig    OpenvpnConfig `yaml:"openvpnConfig"`
	JwtConfig        JwtConfig     `yaml:"jwtConfig"`
	DefaultPort      int           `yaml:"port"`
	BasePath         string        `yaml:"basePath"`
	YamlConfPath     string        `yaml:"yamlConfPath"`
	UserInfoFilePath string        `yaml:"userInfoFilePath"`
}

var Config *BaseConfig

func initConfig(isLoadYamlConf bool) error {
	if !isLoadYamlConf { // 不加载yaml配置就用默认配置
		Config = defaultConf
	} else { //使用yaml配置
		yamlPath := defaultConf.YamlConfPath
		exist, err := file_handle.Exists(yamlPath)
		if err != nil {
			fmt.Printf("parse yaml file error: %s", err.Error())
			Config = defaultConf
			return err
		}
		if !exist { // 不存在默认的yaml文件就生成
			file_handle.GenerateConfigFile(defaultConf, yamlPath)
		}
		file, err := os.Open(yamlPath)
		if err != nil {
			fmt.Printf("parse yaml file error: %s", err.Error())
			Config = defaultConf
			return err
		}
		decoder := yaml.NewDecoder(file)
		err = decoder.Decode(&Config)
		if err != nil {
			fmt.Printf("parse yaml file error: %s", err.Error())
			Config = defaultConf
			return err
		}
		mkdir(Config.BasePath)
	}
	return nil
}

func mkdir(Path string) {
	err := os.MkdirAll(Path, 0755)
	if err != nil {
		fmt.Printf("Failed to create directory %v error: %v", Path, err)
	}
}

func LoadYaml(isLoadYamlConf bool) {
	mkdir(defaultConf.BasePath)
	err := initConfig(isLoadYamlConf)
	if err != nil {
		fmt.Printf("Load configuration error: %s", err.Error())
	}
}
